
#include <Wire.h>  // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
#include "ESP8266WiFi.h"
#include "WifiUDP.h"
#include "NTPClient.h"
#include "TimeLib.h"

const char* ssid = "Wi-Fi SSID";      // Wi-Fi SSID
const char* password = "XXXXXXXX";    // Wi-Fi Password

SSD1306Wire  display(0x3C, 4, 5);
WiFiUDP udp;

// You can specify the time server pool, the offset (in seconds) 
// and the update interval (in milliseconds).
// Set the offset based on your timezone, for example, UTC+8
NTPClient ntp(udp, "pool.ntp.org", 60 * 60 * 8, 60000);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Get time from NTP server");

  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  display.drawString(0, 26, "NTP Time");
  display.display();

  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected");

  ntp.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  ntp.update();
  time_t t = ntp.getEpochTime();
  setTime(t);
  String date = "";
  date += year();
  date += "-";
  date += month();
  date += "-";
  date += day();
  
  Serial.println(date);
  Serial.println(ntp.getFormattedTime());
  display.clear();
  display.drawString(0, 0, date);
  display.drawString(0, 26, ntp.getFormattedTime());
  display.display();
  delay(1000);
}
